<template>
  <div>
    <!-- <BreadCrumb></BreadCrumb> -->

    <div class="content">
      <!-- 首页上面的统计四个表 -->
      <div style="display: flex; justify-content: space-between">
        <!-- 1. 总学生数 -->
        <StatCard label="总学生数" value="120人">
          <template #icon>
            <UserOutlined style="color: #409eff" />
          </template>
        </StatCard>

        <!-- 2. 今日出勤率 -->
        <StatCard label="今日出勤率" value="90%">
          <template #icon>
            <ProfileOutlined style="color: #67c23a" />
          </template>
        </StatCard>

        <!-- 3. 作业完成率 -->
        <StatCard label="作业完成率" value="70%">
          <template #icon>
            <FileTextOutlined style="color: #e6a23c" />
          </template>
        </StatCard>

        <!-- 4. 平均成绩 -->
        <StatCard label="平均成绩" value="85分">
          <template #icon>
            <FundProjectionScreenOutlined style="color: #f56c6c" />
          </template>
        </StatCard>
      </div>

      <!-- 首页下面的卡片统计 -->
      <div
        style="
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          margin-top: 12px;
        "
      >
        <!-- 快捷导航 -->
        <x-card :message="message1" :width="33" :height="height1">
          <div
            style="
              display: flex;
              justify-content: space-between;
              flex-wrap: wrap;
            "
          >
            <!-- 学生管理 -->
            <NavCard :icon="UserOutlined" text="学生管理" to="/admin/student" />
            <!-- 考试管理 -->
            <NavCard :icon="DiffOutlined" text="考试管理" to="/admin/exam" />

            <!-- 作业管理 -->
            <NavCard
              :icon="AppstoreOutlined"
              text="作业管理"
              to="/admin/work"
            />

            <!-- 考勤管理 -->
            <NavCard
              :icon="ScheduleOutlined"
              text="考勤管理"
              to="/admin/attend"
            />

            <!-- 成绩统计 -->
            <NavCard
              :icon="IssuesCloseOutlined"
              text="成绩统计"
              to="/admin/count/overview"
            />

            <!-- 排名榜单 -->
            <NavCard
              :icon="LineChartOutlined"
              text="排名榜单"
              to="/admin/count/rank"
            />

            <!-- 学生成绩分析 -->
            <NavCard
              :icon="BarChartOutlined"
              text="学生成绩分析"
              to="/admin/count/score"
            />

            <!-- 学习趋势分析 -->
            <NavCard
              :icon="DotChartOutlined"
              text="学习趋势分析"
              to="/admin/count/trend"
            />
          </div>
        </x-card>

        <!-- 成绩分布 -->
        <x-card :message="message2" :width="66" :height="height1">
          <div ref="chartRef1" style="width: 100%; height: 300px"></div>
        </x-card>

        <!-- 考勤趋势表 -->
        <x-card
          :message="message3"
          :width="33"
          :height="height2"
          style="margin-top: 12px"
        >
          <div ref="chartRef2" style="width: 100%; height: 240px"></div>
        </x-card>

        <!-- 考勤详情表 -->
        <x-card
          :message="message4"
          :width="33"
          :height="height2"
          style="margin-top: 12px"
        >
          <div ref="chartRef3" style="width: 100%; height: 240px"></div>
        </x-card>

        <!-- 作业完成情况 -->
        <x-card
          :message="message5"
          :width="33"
          :height="height2"
          style="margin-top: 12px"
        >
          <div ref="chartRef4" style="width: 100%; height: 240px"></div>
        </x-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import BreadCrumb from "./BreadCrumb.vue";
import XCard from "./XCard.vue";
import StatCard from "./StatCard.vue"; // 导入 StatCard 组件
import NavCard from "./NavCard.vue";
import { message, Modal, Cascader } from "ant-design-vue";
import {
  UserOutlined,
  FileTextOutlined,
  ProfileOutlined,
  FundProjectionScreenOutlined,
  DiffOutlined,
  AppstoreOutlined,
  ScheduleOutlined,
  IssuesCloseOutlined,
  LineChartOutlined,
  BarChartOutlined,
  DotChartOutlined,
} from "@ant-design/icons-vue";
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import http from "../routerutils/http";

const message1 = ref<string>("快捷导航");
const message2 = ref<string>("成绩分布");
const message3 = ref<string>("出勤趋势");
const message4 = ref<string>("考勤详情");
const message5 = ref<string>("作业完成情况");
const height2 = ref<string>("320px");
const height1 = ref<string>("340px");

// 成绩分布的chart
const chartRef1 = ref<HTMLElement | null>(null);
let chartInstance1: echarts.ECharts | null = null;

const initChart1 = async () => {
  try {
    if (chartRef1.value !== null) {
      const response = await http.get("/api/analysis/score", {
        params: {
          class_id: null,
          program_id: null,
        },
      });
      const obj = response.data.results[0];
      const keys: string[] = Object.keys(obj);
      const values: number[] = Object.values(obj).map((value) =>
        parseInt(value, 10)
      );
      const chart1 = echarts.init(chartRef1.value);
      const option1 = {
        title: {
        text: '考试成绩统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
        tooltip: {},
        xAxis: {
          data: keys,
        },
        yAxis: {},
        series: [
          {
            name: "数量",
            type: "bar",
            data: values,
          },
        ],
      };
      // 初始化或更新图表
      if (!chartInstance1) {
        chartInstance1 = echarts.init(chartRef1.value);
      }
      chartInstance1.setOption(option1);

      // 窗口自适应
      window.addEventListener("resize", () => chartInstance1?.resize());
      // chart1.setOption(option1);
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

// 出勤趋势的chart
const chartRef2 = ref<HTMLElement | null>(null);
let chartInstance2: echarts.ECharts | null = null;

const initChart2 = async () => {
  try {
    if (!chartRef2.value) return;

    // 获取数据
    const response = await http.get("/api/analysis/attend");
    const results = response.data.results;
    
    // 处理数据：转换日期格式和百分比数值
    const processedData = results.map(item => ({
      // date: formatDate(item.date), // 格式化日期
      date: item.date,
      rate: parseFloat(item.attendanceRate.replace('%', '')) // 将"67%"转为67
    }));

    // 分离日期和出勤率数据
    const dateArr = processedData.map(item => item.date);
    const rateArr = processedData.map(item => item.rate);

    // 图表配置
    const option2: echarts.EChartsOption = {
      title: {
        text: '出勤趋势统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const date = params[0].axisValue;
          const rate = params[0].data;
          return `日期: ${date}<br/>出勤率: ${rate}%`;
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dateArr,
        axisLabel: {
          formatter: (value: string) => {
            // 简写日期显示，如"9/20"
            const [year, month, day] = value.split('/');
            return `${month}/${day}`;
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '出勤率',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#1890ff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(24, 144, 255, 0.5)'
              },
              {
                offset: 1,
                color: 'rgba(24, 144, 255, 0.1)'
              }
            ])
          },
          data: rateArr,
          markPoint: {
            data: [
              { type: 'max', name: '最高' },
              { type: 'min', name: '最低' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: '平均' }]
          }
        }
      ]
    };

    // 初始化或更新图表
    if (!chartInstance2) {
      chartInstance2 = echarts.init(chartRef2.value);
    }
    chartInstance2.setOption(option2);

    // 窗口自适应
    const resizeHandler = () => chartInstance2?.resize();
    window.addEventListener('resize', resizeHandler);

    // // 清理事件监听器
    // onUnmounted(() => {
    //   window.removeEventListener('resize', resizeHandler);
    //   chartInstance2?.dispose();
    // });

  } catch (error) {
    console.error("请求失败:", error);
    // 可以添加用户友好的错误提示
    // message.error('获取出勤数据失败，请稍后重试');
  }
};

// 考勤详情的chart
const chartRef3 = ref<HTMLElement | null>(null);
let chartInstance3: echarts.ECharts | null = null;

const initChart3 = async () => {
  try {
    if (chartRef3.value !== null) {
      const response = await http.get("/api/analysis/attenddetail");
      let obj = response.data.results[0];
      const keys: string[] = Object.keys(obj);
      const values: number[] = Object.values(obj).map((value) =>
        parseInt(value, 10)
      );
      let item = {};
      let array = [];
      for (let i = 0; i < keys.length; i++) {
        item = { value: values[i], name: keys[i] };
        array.push(item);
      }
      const chart3 = echarts.init(chartRef3.value);
      const option3 = {
        title: {
          text: "考勤情况统计",
          left: "center",
          textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        tooltip: {},
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: "50%",
            data: array,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      // 初始化或更新图表
      if (!chartInstance3) {
        chartInstance3 = echarts.init(chartRef3.value);
      }
      chartInstance3.setOption(option3);

      // 窗口自适应
      window.addEventListener("resize", () => chartInstance3?.resize());
      // chart3.setOption(option3);chartInstance3
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

// 作业完成情况的chart
const chartRef4 = ref<HTMLElement | null>(null);

// 状态映射表（英文->中文）
const statusMap: Record<string, string> = {
  completed_count: "已完成",
  incomplete_count: "未完成",
  late_count: "迟交",
  total_count: "总计",
};
let chartInstance4: echarts.ECharts | null = null;
const initChart4 = async () => {
  try {
    if (!chartRef4.value) return;

    // 获取数据
    const response = await http.get("/api/analysis/workcomNum");
    const result = response.data.results[0];
    console.log("原始数据:", result);

    // 处理数据：转换为中文并过滤掉总计
    const chartData = Object.entries(result)
      .filter(([key]) => key !== "total_count") // 排除总计
      .map(([key, value]) => ({
        value: parseInt(value as string, 10),
        name: statusMap[key] || key,
      }));

    console.log("图表数据:", chartData);

    // 初始化图表
    const chart4 = echarts.init(chartRef4.value);
    const option4: echarts.EChartsOption = {
      title: {
        text: "作业完成情况统计",
        left: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      legend: {
        orient: "vertical",
        left: "left",
        data: chartData.map((item) => item.name),
      },
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)",
      },
      series: [
        {
          name: "作业状态",
          type: "pie",
          radius: ["40%", "70%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: "{b}: {c} ({d}%)",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: "18",
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: true,
          },
          data: chartData,
        },
      ],
    };
    // 初始化或更新图表
    if (!chartInstance4) {
      chartInstance4 = echarts.init(chartRef4.value);
    }
    chartInstance4.setOption(option4);

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance4?.resize());
    // chart4.setOption(option4);

    // 响应式调整
    window.addEventListener("resize", () => chart4.resize());
  } catch (error) {
    console.error("请求失败:", error);
  }
};
// 检查token是否过期------已在Admin中检查
// const token_search = async () => {
//   let token =
//     localStorage.getItem("token") &&
//     localStorage.getItem("token_is_exp") === "0";
//   if (token) {
//     // router.push('/admin/BackendHome').catch((error) => {
//     //   console.log(error);
//     // });
//     try {
//       let token = localStorage.getItem("token");
//       const res = await http.get("/api/users/check", {
//         headers: {
//           authorization: `Bear ${token}`,
//         },
//       });
//       console.log(res);
//       message.warning(res.data.message);
//     } catch (error: any) {
//       console.log("请求失败", error);
//       message.warning(error.response.data.message);
//     }
//   } else {
//     // router.push("/login");
//     message.warning("您当前登录可能已经过期了！");
//   }
// };
onMounted(() => {
  initChart1();
  initChart2();
  initChart3();
  initChart4();
  // token_search();
});
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
a {
  color: #000;
}
</style>